import os
import json
import logging
from common.middleware import FastApiConfig
from fastapi.params import Depends
from fastapi import FastAPI

"""
主要实现从src下自动导包，且将接口加入到app路由中
"""


def get_app():
    app = FastAPI(**FastApiConfig)
    join_queue = set()
    api_dir = os.listdir("src")
    for api in api_dir:
        if ".py" in api or ".pyc" in api or "__pycache__" in api or api[0] == ".":
            continue
        try:
            package = os.listdir(f"src/{api}")
        except:
            continue
        for i in package:
            if i == "__init__.py" or i == "__pycache__":
                continue
            i = i.replace(".py", "").replace(".pyc", "")
            try:
                exec(f"from src.{api}.{i} import *")
            except Exception as e:
                logging.warning(f"import package error[{api}]")

    apis = dict(locals())
    for k, v in apis.items():
        try:
            if "BaseApi" in str(v.mro()) and len(v.mro()) >= 3:
                try:
                    try:
                        exit_path = v.path
                    except Exception as e:
                        logging.warning(f"filter out [{v.__name__}]")
                        continue
                    # app.add_api_route(**v().get_router, endpoint=v().deal)
                    app.add_api_route(**v().get_router, endpoint=v().deal, dependencies=[Depends(v.prepare_envrioment)])
                    join_queue.add("Succeed to join [ " + str(v().get_router) + " ]")
                except Exception as e:
                    logging.exception(str(e))
                    logging.warning(f"[API] {v.__name__} error")
        except Exception as e:
            logging.info("warn=", str(v))

    return app, join_queue


if __name__ == '__main__':
    import uvicorn

    app = get_app()
    uvicorn.run(app, host='0.0.0.0', access_log=True, use_colors=True)
